package com.crazy.mybatis.gerenator.service.java;

import java.io.FileWriter;
import java.io.IOException;

import com.crazy.mybatis.gerenator.service.common.Constants;

public class MapperFileWriter {

	private FileWriter fileWriter;

	public MapperFileWriter(FileWriter fileWriter) {
		this.fileWriter = fileWriter;
	}

	public void write(ClassMetaData meta) throws IOException {
		// package com.crazy;
		fileWriter.write("package" + Constants.SPACE + meta.getPackageName() + Constants.SEMICOLON);
		println(2);
		// import com.crazy.XXX;
		for (String clazz : meta.getImportClasses()) {
			fileWriter.write("import" + Constants.SPACE + clazz + Constants.SEMICOLON);
			println();
		}
		println();
		// class interface XxxMaper {
		fileWriter.write("public" + Constants.SPACE + meta.getClassType() + Constants.SPACE + meta.getClassName()
				+ Constants.SPACE + Constants.OPEN);
		println(2);
		// write methods
		for (MapperMethodMetaData m :meta.getMethodList()) {
			intent(1);
			fileWriter.write(m.getReturnClassName());
			if (m.getGenericClassName() != null) {
				fileWriter.write("<" + m.getGenericClassName() + ">");
			}
			fileWriter.write(Constants.SPACE + m.getMethodName() + "(" + m.getParameterClassName() + Constants.SPACE + m.getParameter() + ")" + Constants.SEMICOLON);
			println(2);
		}
		fileWriter.write(Constants.CLOSE);
	}
	
	private void println() throws IOException {
		println(1);
	}

	private void println(int n) throws IOException {
		while (n > 0) {
			n--;
			fileWriter.write(Constants.LINE_END);
		}
	}

	private void intent(int n) throws IOException {
		while (n > 0) {
			n--;
			fileWriter.write(Constants.INTENT);
		}
	}
}
